<?php
	function validateEmail($string) {
		return  preg_match("/^(\w+((-\w+)|(\w.\w+))*)\@(\w+((\.|-)\w+)*\.\w+$)/",$string);
	}
	
	$host="localhost"; // Host name
	$username="root"; // Mysql username
	$password=""; // Mysql password
	$db_name="JSU_Database"; // Database name
	$tbl_name="Student"; // Table name

	// Connect to server and select database.
	mysql_connect($host, $username, $password)or die("cannot connect");
	mysql_select_db($db_name)or die("cannot select DB: ".mysql_error());

	// username and password sent from form
	$email=$_POST['email'];
	$curpwd=$_POST['curPwd'];
	$newpwd=$_POST['newPwd'];
	
	// To protect against MySQL injection
	if (!validateEmail($email))
		echo "Email is not valid.<br>";
	/*if (!filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL))
		echo "Email is not valid.<br>";
		
	$email = stripslashes($email);
	$curpwd = stripslashes($curpwd);
	$newpwd = stripslashes($newpwd);
	
	$email = mysql_real_escape_string($email);
	$curpwd = mysql_real_escape_string($curpwd);
	$newpwd = mysql_real_escape_string($newpwd);
	
	$email = htmlspecialchars($email);
	$curpwd = htmlspecialchars($curpwd);
	$newpwd = htmlspecialchars($newpwd);
	
	//protect against email injection and buffer overflows
	if (strlen($email) < 50)
		//$email = safeEmail($email);
	else
		echo "Email is too long";*/
	
	// check passwords
	session_start();
	$JNo = $_SESSION['JNo'];
	$getPwd = mysql_query("SELECT PW FROM $tbl_name WHERE '$JNo' = JNo AND '$curpwd' = PW");
	$row = mysql_fetch_row($getPwd);
	$dbPwd = $row[0];
	if ($email == null || $curpwd == null || $newpwd == null)
		echo "Please fill out all data";
	else if ($curpwd != $dbPwd)
		echo "Current password is incorrect";
	else if ($newpwd == $dbPwd)
		echo "New password must be changed.";
	else if ((strlen($newpwd) < 8) || (strlen($newpwd) > 16))
		echo "Password must be between 8 and 16 characters.";
	else {
		mysql_query("UPDATE $tbl_name SET PW = '$newpwd', Email = '$email' WHERE JNo = '$JNo'");
		header("location:updated.php");
	}
	//encrypt password
	//$RSA = new RSA_Handler();
	//$keys = $RSA->generate_keypair(1024);
	//$encrypted_pwd = $RSA->encrypt($userpwd, $keys[0]);
	//$decrypted_pwd = $RSA->decrypt($encrypted_pwd, $keys[1]);

	

	// Mysql_num_row is counting table row
	//$count=mysql_num_rows($result);
	// If result matched $JNo and $userpwd, table row must be 1 row

	/*if($result){
	// Register $JNo, $userpwd and redirect to file "login_success.php"
	$_SESSION[$JNo];
	$_SESSION[$userpwd];
	header('location:loginsuccess.php');
	}
	else {
	echo "Wrong Username or Password";
	}*/
?>